/*
 * @(#)GetImageServlet.java
 *
 * Copyright (c) 2005 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */

package com.dcivision.dms.web;

// io imports
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;

/**
 * <p>
 * Class Name: GetImageServlet.java
 * </p>
 * <p>
 * Description: get some list data and send to applet
 * </p>
 * 
 * @author Beyond Qu
 * @company DCIVision Limited
 * @creation date 14/01/2005
 * @version $Revision: 1.7.2.1 $
 */

public class EmailArchiveGetImageServlet extends HttpServlet {

  public static final String REVISION = "$Revision: 1.7.2.1 $";

  private static final Log log = LogFactory.getLog(EmailArchiveGetImageServlet.class);
  /**
   * init This function will be called only once, when the servlet is called for the first time to initialize
   * servletToApplet object and to perform one time activities
   * 
   * @param config is a ServletConfig object
   * @throws ServletException exception
   */
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }

  /**
   * Process the HTTP doGet request.
   * 
   * @param request is a HttpServletRequest object
   * @param response is a HttpServletResponse object
   * 
   * @throws ServletException exception
   * @throws IOException exception
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletOutputStream fos = response.getOutputStream();
    Connection conn = null;
    try {
      conn = DataSourceFactory.getConnection();
      SessionContainer sessionContainer = this.getSessionContainer(request);
      String attachmentDocumentID = request.getParameter("attachmentDocumentID");
      String catchFileName = request.getParameter("catchFileName");
      String attachFileName = request.getParameter("attachFileName");
      String download = request.getParameter("download");
      String cachePath = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_CACHEFOLDER_PATH);
      String trueFilePath = cachePath + catchFileName;
      DocumentOperationManager documentOperationManager = new DocumentOperationManager(sessionContainer, conn);
      if (attachmentDocumentID != null) {
        InputStream docInputStream = documentOperationManager.getDocPhysicalFileContentByDocumentID(TextUtility
            .parseIntegerObj(attachmentDocumentID));
        operateOutputstream(response, docInputStream, fos, download != null ? true : false, attachFileName);
        docInputStream.close();
      } else {
        File file = new File(trueFilePath);
        if (file.exists()) {
          DataInputStream inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(trueFilePath)));
          operateOutputstream(response, inputStream, fos, download != null ? true : false, attachFileName);
          inputStream.close();
        } else {
          fos.flush();
        }
      }

    } catch (Exception e) {

    } finally {
      try {
        conn.close();
      } catch (Exception e) {
        log.error(e);
      } finally {
        conn = null;
      }
      fos.close();
    }
  }

  /**
   * Process the HTTP doPost request. which will call doGet(...) method.
   * 
   * @param request is a HttpServletRequest object
   * @param response is a HttpServletResponse object
   * 
   * @throws ServletException exception
   * @throws IOException exception
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doGet(request, response);
  }

  /**
   * getConnection
   * 
   * @param request The HTTP request
   * @return The connection which pre-opened and stored in request
   */
  public Connection getConnection(HttpServletRequest request) {
    return ((Connection) request.getAttribute(GlobalConstant.DB_KEY));
  }

  /**
   * getSessionContainer
   * 
   * @param request The HTTP request
   * @return The Session Container
   */
  public SessionContainer getSessionContainer(HttpServletRequest request) {
    SessionContainer ctx = (SessionContainer) request.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    if (ctx == null) {
      ctx = new SessionContainer();
      request.getSession().setAttribute(GlobalConstant.SESSION_CONTAINER_KEY, ctx);
    }
    return (ctx);
  }

  public void operateOutputstream(HttpServletResponse response, InputStream inputStream, ServletOutputStream fos, boolean isDownload,
      String fileName) throws Exception {
    response.addHeader("Content-Transfer-Encoding", "base64");
    if (isDownload) {
      response.addHeader("Content-Disposition", "attachment; filename=" + fileName + "\"");
    } else {
      response.addHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
    }
    int bufferSize = 8192;
    byte[] buffer = new byte[bufferSize];
    int length = -1;
    while ((length = inputStream.read(buffer, 0, bufferSize)) != -1) {
      fos.write(buffer, 0, length);
    }
    fos.flush();
  }

}
